<template>
  <div>
    <el-container class="app-container app-containerdetp app-containerMoneytabel">
      <el-aside class="aside-box" >
        <el-card class="box-card">
          <div slot="header" class="clearfix"><span>组织机构</span></div>
          <el-tree class="filter-tree" node-key="id" 
            :show-checkbox="true" :check-strictly="true"
            @node-click="handleNodeChange" 
            :data="orgDatas" :props="defaultProps" 
            default-expand-all :filter-node-method="filterNode"
            :expand-on-click-node="false" ref="tree" :render-content="renderContent">
          </el-tree>
        </el-card>
      </el-aside>
      <el-main  class="main-box">
        <div class="filter-container">
          <el-input size="small" @keyup.enter.native="handleFilter" placeholder="请输入部门名称" style="width: 200px;" class="filter-item"
            v-model="listQuery.deptName">
          </el-input>
          <el-button size="small" style="marginLeft: 15px;" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button size="small" class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
        </div>
        <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit
          highlight-current-row>
          <el-table-column type="index" width="50" label="序号"></el-table-column>>
          <el-table-column label="部门名称" align="center">
            <template slot-scope="scope">
              {{scope.row.name}}
            </template>
          </el-table-column>

          <el-table-column align="center" prop="created_at" label="注册时间">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span v-if="scope.row.createTime">{{scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
            :page-sizes="[10,20,30, 50]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-main>
    </el-container>
    <!--添加修改弹出层-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="80px" style='width: calc(100% - 100px); margin-left:50px;; margin-right:50px'>
        <el-input v-model="temp.id" v-show="false"></el-input>
        <el-input v-model="temp.parentId" v-show="false"></el-input>
        <el-form-item label="类型" prop="deptType">
          <el-select size="small" v-model="temp.deptType" placeholder="请选择">
            <el-option v-for="item in deptTypeOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input size="small" v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input size="small" v-model="temp.phone"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="no">
          <el-input size="small" v-model="temp.no"></el-input>
        </el-form-item>
        <el-form-item label="地区" prop="areaCode"  class="dialog-areaCode_dept">
          <region-selector  :province="region.province" :city="region.city" :area="region.area" 
            :street="region.street" :community="region.community"
             @region="setAreaCode" >
          </region-selector>
          <el-input style="display:none" type="hidden" v-model="temp.areaCode"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">提交</el-button>
        <el-button v-else type="primary" @click="updateData">更新</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getTree,
  queryPage,
  create,
  update,
  deleteById,
  queryInfo
} from "@/api/dept";
import treeTable from "@/components/TreeTable";
import RegionSelector from "@/components/RegionSelector";
import DetpTree from "../components/DetpTree";
import { packRegionCode } from "@/utils/region";
import { validateMobilePhone } from "@/utils/validate";

export default {
  name: "dept",
  components: { treeTable, RegionSelector, DetpTree },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!validateMobilePhone(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      list: null,
      total: 0,
      listLoading: false,
      checkOrgId: null,
      listQuery: {
        page: 1,
        size: 10,
        deptName: null,
        orgId: null,
        sort: "+id"
      },
      dialogFormVisible: false,
      selectedOrg: false,
      dialogStatus: "",
      textMap: {
        update: "更新",
        create: "添加"
      },
      parent: {
        id: null,
        name: null
      },
      temp: {
        id: null,
        name: null,
        areaCode: null,
        deptType: "0",
        parentId: null,
        phone: null,
        no: null
      },
      region: {
        province: 0,
        city: 0,
        area: 0,
        street: 0,
        community: 0
      },
      rules: {
        deptType: [
          { required: true, message: "请选择类型", trigger: "change" }
        ],
        name: [
          { required: true, message: "请选择输入部门名称", trigger: "change" }
        ],
        no: [
          { required: true, message: "请选择输入部门编码", trigger: "change" }
        ],
        phone: [
          { required: true, message: "请选择输入电话", trigger: "change" },
          { validator: validatePhone}
        ],
        areaCode: [{ required: true, message: "请选择地区", trigger: "change" }]
      },
      deptTypeOptions: this.$store.state.dict.options['deptType'],
      filterText: "",
      orgDatas: [],
      defaultProps: {
        children: "children",
        label: "label",
        id: "id"
      }
    };
  },
  mounted: function() {
    this.fetchDeptData();
    this.queryOrgData();
  },
  methods: {
    //org start
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    queryOrgData() {
      getTree().then(response => {
        this.orgDatas = response.data;
      });
    },
    handleNodeChange(item, node, self) {
      this.listQuery.orgId = item.id;
      this.fetchDeptData();
      this.checkOrgId = item.id;
      this.$refs.tree.setCheckedKeys([item.id]);
      this.setOrgRegion(item.id)
      this.selectedOrg = true
    },
    setOrgRegion(id){
      queryInfo(id).then(res=>{
        //地区处理
        let areaCode = res.data.areaCode
        if (areaCode && areaCode.length > 5) {
          this.region = packRegionCode(areaCode);
          this.temp.areaCode = areaCode
        }
      })
    },
    handleUpdateOrg(data) {
      queryInfo(data.id).then(response => {
        this.temp = Object.assign({}, response.data);
        //地区处理
        if (this.temp.areaCode && this.temp.areaCode.length > 5) {
          this.region = packRegionCode(this.temp.areaCode);
        }
        this.dialogStatus = "update";
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      });
    },
    setAreaCode(value) {
      if (value.code) {
        this.temp.areaCode = value.code;
      }
    },
    remove(node, data) {
      const loading = this.$loading({
        lock: true,
        text: "提交中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      setTimeout(() => {
        loading.close();
      }, 800);
      this.$confirm("删除后不可恢复, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteById(data.id).then(() => {
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex(d => d.id === data.id);
          children.splice(index, 1);
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
          });
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消"
        });
      });

      
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span>
            <el-button
              size="medium"
              type="text"
              on-click={() => this.handleUpdateOrg(data)}
            >
              编辑
            </el-button>
            <el-button
              size="medium"
              type="text"
              on-click={() => this.remove(node, data)}
            >
              删除
            </el-button>
          </span>
        </span>
      );
    },
    append() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.pid = this.temp.data.id;
          create(this.temp).then(() => {
            const newChild = {
              label: this.temp.name,
              url: this.temp.url,
              children: []
            };
            if (!this.temp.data.children) {
              this.$set(this.temp.data, "children", []);
            }
            this.temp.data.children.push(newChild);
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    //dept start
    fetchDeptData() {
      this.listLoading = true;
      queryPage(this.listQuery).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.fetchDeptData();
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.fetchDeptData();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.fetchDeptData();
    },
    handleCreate() {
      if(!this.checkOrgId){
        this.$message.error('请先选择右侧组织机构');
        return
      }
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.listQuery.orgId) {
            this.temp.parentId = this.listQuery.orgId;
          }
          create(this.temp).then(() => {
            this.fetchDeptData()
            this.queryOrgData();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      //地区处理
      if (this.temp.areaCode && this.temp.areaCode.length > 5) {
        this.region = packRegionCode(this.temp.areaCode);
      }
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          update(tempData).then(() => {
            this.queryOrgData()
            this.fetchDeptData()
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleDelete(row) {
      const loading = this.$loading({
        lock: true,
        text: "提交中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      setTimeout(() => {
        loading.close();
      }, 800);
      this.$confirm("删除后不可恢复, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteById(row.id).then(() => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000
        });
        const index = this.list.indexOf(row);
        this.list.splice(index, 1);
      });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消"
        });
      });
    },
    resetTemp() {
      this.temp = {
        id: null,
        name: null,
        areaCode: this.temp.areaCode,
        no: null,
        deptType: "0",
        parentId: null
      };
    },
    resetRegion(){
      this.region = {
        province: 0,
        city: 0,
        area: 0,
        street: 0,
        community: 0
      };
    }
  }
};
</script>

<style scoped>
.main-box {
  padding: 0;
  width: calc(100% - 320px);
  margin-left: 20px;
}

.app-container {
  overflow: hidden;
}
.roleNames-role-checkbox {
  border: 1px solid red;
}
.filter-container {
  margin-bottom: 20px;
  overflow: hidden;
}

.pagination-container {
  margin-top: 25px;
  overflow: hidden;
  display: flex;
  justify-content: flex-end;
}
</style>
